//
// File:	Config.cpp
// Author:	Thomas TISSOT-DUPONT
// Login:	<thomas.tissotdupont@free.fr>
//
// Created:	17/04/2010 at 19:33:06
// Purpose:	
//
#include "Config.hpp"
#include "Inputs.hpp"
#include "Trace.hpp"

const std::string Config::st_configNodeName = "config";

//------------------------------------------------------------------
// Config File Path
//------------------------------------------------------------------
std::string Config::GetConfigFilePath()
{
	return "cfg/config.cfg";
}

//------------------------------------------------------------------
// Parse From File
//------------------------------------------------------------------
bool Config::ParseFromFile(const std::string &filePath)
{
	Parser::Clear();
	if (!Parser::ParseFromFile(filePath))
		return false;
	Trace::debug << "Opened Configuration File: " << filePath << std::endl;
	return true;
}

//------------------------------------------------------------------
// Write To File
//------------------------------------------------------------------
//FIXME: should I write a Parser::WriteToFile() function instead ?
bool Config::WriteToFile(const std::string &filePath)
{
	//Construct buffer
	std::string fileBuffer = st_configNodeName + Parser::stNewLine + Parser::stOpenBlock + Parser::stNewLine;
	Parser::Element *pConfigElement = m_rootElement.FindChild(st_configNodeName);
	if (pConfigElement != NULL)
	{
		std::map<std::string, Variant>::const_iterator it = pConfigElement->GetKeyValues().begin();
		std::map<std::string, Variant>::const_iterator ite = pConfigElement->GetKeyValues().end();
		for (; it != ite; ++it)
		{
			if (it->first.empty())
				continue;
			fileBuffer += it->first + Parser::stKeyEnd + Parser::stSpace + it->second.ToString() + Parser::stValueEnd + Parser::stNewLine;
		}
	}
	fileBuffer += Parser::stCloseBlock + Parser::stNewLine;

	//Write buffer to file
	if (!Parser::File::WriteContents(filePath, fileBuffer))
		return false;
	Trace::debug << "Wrote Configuration File: " << filePath << std::endl;
	return true;
}

//------------------------------------------------------------------
// CVAR
//------------------------------------------------------------------
void Config::SetCvar(const std::string &key, const Variant &value)
{
	Parser::Element *pConfigElement = m_rootElement.FindChild(st_configNodeName);
	if (pConfigElement == NULL)
		return;
	pConfigElement->AddKeyValue(key, value.ToString());
}

bool Config::HasCvar(const std::string &key) const
{
	Parser::Element *pConfigElement = m_rootElement.FindChild(st_configNodeName);
	if (pConfigElement == NULL)
		return false;
	return pConfigElement->HasKey(key);
}

Variant Config::GetCvar(const std::string &key, const Variant &defaultValue /* = Variant() */) const
{
	Parser::Element *pConfigElement = m_rootElement.FindChild(st_configNodeName);
	if (pConfigElement == NULL)
		return defaultValue;
	return pConfigElement->GetValueForKey(key, defaultValue);
}
